package sprinklerbee.views;

import javax.swing.JPanel;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.Time;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;
import java.util.Vector;

import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.SpinnerDateModel;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.JCheckBox;
import java.awt.GridLayout;
import javax.swing.JRadioButton;
import javax.swing.JComboBox;

import sprinklerbee.factory.ServiceFactory;
import sprinklerbee.model.Group;
import sprinklerbee.model.Scheduler;
import sprinklerbee.model.Sprinkler;
import sprinklerbee.service.SchedulerService;
import sprinklerbee.utils.CommonUtils;
import sprinklerbee.utils.JComboBoxUtils;
import sprinklerbee.utils.MemoryCache;
import sprinklerbee.utils.SprinklerTabelModel;
import sun.awt.image.PixelConverter.Bgrx;

import java.awt.Dimension;
import java.awt.FlowLayout;
@SuppressWarnings("serial")
public class ScheduleSettingPanel extends JPanel{

	private JButton btnAdd;
	private JButton btnClear;
	private JButton btnDelete;
	private static JCheckBox chckbxMon;
	private static JCheckBox chckbxFri;
	private static JCheckBox chckbxWed;
	private static JCheckBox chckbxTue;
	private static JCheckBox chckbxSat;
	private static JCheckBox chckbxSun;
	private static JCheckBox chckbxThu;
	private static JPanel panel;
	private static JPanel panel_1;
	private static JRadioButton groupBtn;
	private static JRadioButton sprinklerBtn;
	private JPanel radioPanel;
	private static JRadioButton northBtn;
	private static JRadioButton eastBtn;
	private static JRadioButton westBtn;
	private static JRadioButton southBtn;
	private JPanel sprinklerPanel;
	private static JComboBox sprinkler_status;
	private JButton btnEnable;
	private JButton btnDisable;
	private JPanel panel_2;
	private JButton btnOn;
	private JButton btnOff;
	private String sprinklerName;
	private final static JSpinner fromTimeSpinner = new JSpinner( new SpinnerDateModel() );
	private final static JSpinner toTimeSpinner = new JSpinner( new SpinnerDateModel() );
	private static Map<String, String> criteria=new HashMap<String, String>();
	
	public ScheduleSettingPanel(){
		FlowLayout flowLayout = (FlowLayout) getLayout();
		flowLayout.setAlignment(FlowLayout.LEFT);
		
		setBorder(new TitledBorder("Schedule Settings"));	 
		
		panel = new JPanel();
		add(panel);
		panel.setLayout(new GridLayout(2, 1, 10, 0));
		
		groupBtn = new JRadioButton("Group", true);
		panel.add(groupBtn);
		
		sprinklerBtn = new JRadioButton("Specific Sprinkler", false);
		panel.add(sprinklerBtn);
		
		JPanel btnSchedulePanel = new JPanel();

		ButtonGroup bg = new ButtonGroup();
		bg.add(groupBtn);
		bg.add(sprinklerBtn);
		
		radioPanel = new JPanel();
		panel.add(radioPanel);
		radioPanel.setLayout(new GridLayout(1, 1));
		
		northBtn = new JRadioButton("North", true);
		northBtn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				refreshSchedulerPanel();
			}
		});
		radioPanel.add(northBtn);
		
		eastBtn = new JRadioButton("East", false);
		eastBtn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				refreshSchedulerPanel();
			}
		});
		radioPanel.add(eastBtn);
		
		westBtn = new JRadioButton("West", false);
		westBtn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				refreshSchedulerPanel();
			}
		});
		radioPanel.add(westBtn);
		
		southBtn = new JRadioButton("South", false);
		southBtn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				refreshSchedulerPanel();
			}
		});
		radioPanel.add(southBtn);
		
		ButtonGroup bgGroup = new ButtonGroup();
		bgGroup.add(northBtn);
		bgGroup.add(eastBtn);
		bgGroup.add(southBtn);
		bgGroup.add(westBtn);
		
		sprinklerPanel = new JPanel();
		panel.add(sprinklerPanel);
		sprinklerPanel.setLayout(new GridLayout(1, 1));
		
		sprinkler_status = new JComboBox();
		sprinkler_status.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				refreshSchedulerPanel();
			}
		});
		sprinkler_status.setPreferredSize(new Dimension(50, 20));
		sprinkler_status.setEnabled(false);
		List<String> list=ServiceFactory.getSprinklerServiceInstance().getAllSprinklers();
		JComboBoxUtils.fillComboBox(sprinkler_status, "Please choose a sprinkler", list);
		sprinklerPanel.add(sprinkler_status);
		
		groupBtn.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				if (groupBtn.isSelected()) {
					northBtn.setEnabled(true);
					southBtn.setEnabled(true);
					westBtn.setEnabled(true);
					eastBtn.setEnabled(true);
					sprinkler_status.setEnabled(false);
				}
			}
		});
		
		sprinklerBtn.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				if (sprinklerBtn.isSelected()) {
					northBtn.setEnabled(false);
					southBtn.setEnabled(false);
					westBtn.setEnabled(false);
					eastBtn.setEnabled(false);
					sprinkler_status.setEnabled(true);
				}
			}
		});
		
		panel_1 = new JPanel();
		FlowLayout flowLayout_1 = (FlowLayout) panel_1.getLayout();
		flowLayout_1.setAlignment(FlowLayout.LEFT);
		flowLayout_1.setHgap(3);
		add(panel_1);
		
		chckbxMon = new JCheckBox("Mon");
		panel_1.add(chckbxMon);
		
		chckbxTue = new JCheckBox("Tue");
		panel_1.add(chckbxTue);
		
		chckbxWed = new JCheckBox("Wed");
		panel_1.add(chckbxWed);
		
		chckbxThu = new JCheckBox("Thu");
		panel_1.add(chckbxThu);
		
		chckbxFri = new JCheckBox("Fri");
		panel_1.add(chckbxFri);
		
		chckbxSat = new JCheckBox("Sat");
		panel_1.add(chckbxSat);
		
		chckbxSun = new JCheckBox("Sun");
		panel_1.add(chckbxSun);
		
		JLabel lbl_fromTime = new JLabel();
		panel_1.add(lbl_fromTime);
		lbl_fromTime.setText("From");
		
		panel_1.add(fromTimeSpinner);
		JSpinner.DateEditor timeEditor = new JSpinner.DateEditor(fromTimeSpinner, "HH:mm");
		fromTimeSpinner.setEditor(timeEditor);
		fromTimeSpinner.setValue(new Date());
		
		JLabel lbl_toTime = new JLabel();
		panel_1.add(lbl_toTime);
		lbl_toTime.setText("To");
		
		
		panel_1.add(toTimeSpinner);
		JSpinner.DateEditor timeEditor1 = new JSpinner.DateEditor(toTimeSpinner, "HH:mm");
		toTimeSpinner.setEditor(timeEditor1);
		toTimeSpinner.setValue(new Date()); // will only show the current time
		
		panel_2 = new JPanel();
		panel_1.add(panel_2);
		add(btnSchedulePanel, BorderLayout.SOUTH);
		
		btnAdd = new JButton();
		btnAdd.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				Scheduler scheduler=new Scheduler();
				scheduler.setStarttime(CommonUtils.transferTime((Date) fromTimeSpinner.getValue()));
				scheduler.setEndtime(CommonUtils.transferTime((Date)toTimeSpinner.getValue()));
				scheduler.setMon(chckbxMon.isSelected()?true:false);
				scheduler.setTue(chckbxTue.isSelected()?true:false);
				scheduler.setWed(chckbxWed.isSelected()?true:false);
				scheduler.setThur(chckbxThu.isSelected()?true:false);
				scheduler.setFri(chckbxFri.isSelected()?true:false);
				scheduler.setSat(chckbxSat.isSelected()?true:false);
				scheduler.setSun(chckbxSun.isSelected()?true:false);
				scheduler.setCreatetime(new Date());
				scheduler.setStatus("Active");
				String groupName="";
				if (groupBtn.isSelected()&&validateSchedule()) {
					if (northBtn.isSelected()) {
						groupName="North";
					}
					if (southBtn.isSelected()) {
						groupName="South";
					}
					if (westBtn.isSelected()) {
						groupName="West";
					}
					if (eastBtn.isSelected()) {
						groupName="East";
					}
					if (ServiceFactory.getSchedulerServiceInstance().addSchedulerByGroup(groupName, scheduler)) {
						JOptionPane.showMessageDialog(null, "The schedules have been saved successfully.");
						MemoryCache.refreshMemoryCache();
						refreshSchedulerPanel();
					}
				}
				
				if (sprinklerBtn.isSelected()&&validateSchedule()) {
					Sprinkler sprinkler=new Sprinkler();
					sprinkler.setName(sprinkler_status.getSelectedItem().toString());
					scheduler.setSprinkler(sprinkler);
					sprinkler.setStatus("Active");
					if (ServiceFactory.getSchedulerServiceInstance().addSchedule(sprinkler_status.getSelectedItem().toString(),scheduler)) {
						JOptionPane.showMessageDialog(null, "The schedule has been saved successfully.");
						MemoryCache.refreshMemoryCache();
						refreshSchedulerPanel();
					}
				}
			}
		});
		btnAdd.setText("Add");
		btnAdd.setToolTipText("Add New Schedule");
		
		btnDelete = new JButton();
		btnDelete.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				Scheduler scheduler=new Scheduler(SchedulePanel.getDeleteItemId());
				if (ServiceFactory.getSchedulerServiceInstance().delSchedule(scheduler)) {
					JOptionPane.showMessageDialog(null, "The schedule has been deleted successfully.");
					MemoryCache.refreshMemoryCache();
					refreshSchedulerPanel();
				}
			}
		});
		btnDelete.setText("Delete");
		btnDelete.setToolTipText("Delete Schedule");
	    
		btnSchedulePanel.add(btnAdd);
		btnSchedulePanel.add(btnDelete);
		
		btnClear = new JButton();
		btnClear.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				// Clear the panel.
				chckbxFri.setSelected(false);
				chckbxMon.setSelected(false);
				chckbxTue.setSelected(false);
				chckbxWed.setSelected(false);
				chckbxThu.setSelected(false);
				chckbxSat.setSelected(false);
				chckbxSun.setSelected(false);
			}
		});
		btnClear.setText("Clear");
		btnClear.setToolTipText("Clear");
		btnSchedulePanel.add(btnClear);
		
		btnOn = new JButton("Activate");
		btnOn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				if (groupBtn.isSelected()){
					Group group=null;
					if (northBtn.isSelected()) {
						group=new Group("North");
					}
					if (southBtn.isSelected()) {
						group=new Group("South");
					}
					if (westBtn.isSelected()) {
						group=new Group("West");
					}
					if (eastBtn.isSelected()) {
						group=new Group("East");
					}
					Scheduler scheduler=new Scheduler();
					scheduler.setStatus("Active");
					if (ServiceFactory.getSchedulerServiceInstance().updateSchedule(group,scheduler)) {
						JOptionPane.showMessageDialog(null, "Update successfully!");
						MemoryCache.refreshMemoryCache();
						refreshSchedulerPanel();
					}
				}else if (sprinklerBtn.isSelected()){
					if (sprinkler_status.getSelectedIndex()!= 0){
						Scheduler scheduler=new Scheduler();
						scheduler.setStatus("Active");
						scheduler.setSprinkler(new Sprinkler(sprinkler_status.getSelectedItem().toString()));
						if (ServiceFactory.getSchedulerServiceInstance().updateSchedule(scheduler)) {
							JOptionPane.showMessageDialog(null, "Update successfully!");
							MemoryCache.refreshMemoryCache();
							refreshSchedulerPanel();
						}
					}
				}
			}
		});
		btnSchedulePanel.add(btnOn);
		
		btnOff = new JButton("Deactivate");
		btnOff.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (groupBtn.isSelected()){
					Group group=null;
					if (northBtn.isSelected()) {
						group=new Group("North");
					}
					if (southBtn.isSelected()) {
						group=new Group("South");
					}
					if (westBtn.isSelected()) {
						group=new Group("West");
					}
					if (eastBtn.isSelected()) {
						group=new Group("East");
					}
					Scheduler scheduler=new Scheduler();
					scheduler.setStatus("Unactive");
					if (ServiceFactory.getSchedulerServiceInstance().updateSchedule(group,scheduler)) {
						JOptionPane.showMessageDialog(null, "Update successfully!");
						MemoryCache.refreshMemoryCache();
						refreshSchedulerPanel();
					}
				}else if (sprinklerBtn.isSelected()){
					if (sprinkler_status.getSelectedIndex()!= 0){
						Scheduler scheduler=new Scheduler();
						scheduler.setStatus("Unactive");
						scheduler.setSprinkler(new Sprinkler(sprinkler_status.getSelectedItem().toString()));
						if (ServiceFactory.getSchedulerServiceInstance().updateSchedule(scheduler)) {
							JOptionPane.showMessageDialog(null, "Update successfully!");
							MemoryCache.refreshMemoryCache();
							refreshSchedulerPanel();
						}
					}
				}
			}
		});
		btnSchedulePanel.add(btnOff);
		
		btnEnable = new JButton("Enable");
		btnEnable.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (groupBtn.isSelected()) {
					Group group=null;
					if (northBtn.isSelected()) {
						group=new Group("North");
					}
					if (southBtn.isSelected()) {
						group=new Group("South");
					}
					if (westBtn.isSelected()) {
						group=new Group("West");
					}
					if (eastBtn.isSelected()) {
						group=new Group("East");
					}
					if (ServiceFactory.getSprinklerServiceInstance().updateSprinklerStatus(group, "Enabled")) {
						JOptionPane.showMessageDialog(null, "Update successfully!");
						MemoryCache.refreshMemoryCache();
						refreshSchedulerPanel();
					}
				}
				if (sprinklerBtn.isSelected()) {
					if (sprinkler_status.getSelectedIndex()==0) {
						JOptionPane.showMessageDialog(null, "Please choose a sprinkler!");
					}else{
						String sprinklerName=sprinkler_status.getSelectedItem().toString();
						if (ServiceFactory.getSprinklerServiceInstance().updateSprinklerStatus(new Sprinkler(sprinklerName),"Enabled")) {
							JOptionPane.showMessageDialog(null, "Update successfully!");
							MemoryCache.refreshMemoryCache();
							refreshSchedulerPanel();
						}
					}
				}
			}
		});
		btnSchedulePanel.add(btnEnable);
		btnEnable.setToolTipText("Enable");
		
		btnDisable = new JButton("Disable");
		btnDisable.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (groupBtn.isSelected()) {
					Group group=null;
					if (northBtn.isSelected()) {
						group=new Group("North");
					}
					if (southBtn.isSelected()) {
						group=new Group("South");
					}
					if (westBtn.isSelected()) {
						group=new Group("West");
					}
					if (eastBtn.isSelected()) {
						group=new Group("East");
					}
					if (ServiceFactory.getSprinklerServiceInstance().updateSprinklerStatus(group, "Disabled")) {
						JOptionPane.showMessageDialog(null, "Update successfully!");
						MemoryCache.refreshMemoryCache();
						refreshSchedulerPanel();
					}
				}
				if (sprinklerBtn.isSelected()) {
					if (sprinkler_status.getSelectedIndex()==0) {
						JOptionPane.showMessageDialog(null, "Please choose a sprinkler!");
					}else{
						sprinklerName=sprinkler_status.getSelectedItem().toString();
						if (ServiceFactory.getSprinklerServiceInstance().updateSprinklerStatus(new Sprinkler(sprinklerName),"Disabled")) {
							JOptionPane.showMessageDialog(null, "Update successfully!");
							MemoryCache.refreshMemoryCache();
							refreshSchedulerPanel();
						}
					}
				}
			}
		});
		btnSchedulePanel.add(btnDisable);
		btnDisable.setToolTipText("Disable");
	}
	
	public static void selectScheduler(Scheduler scheduler){
		northBtn.setEnabled(false);
		southBtn.setEnabled(false);
		westBtn.setEnabled(false);
		eastBtn.setEnabled(false);
		sprinklerBtn.setSelected(true);
		groupBtn.setSelected(false);
		sprinkler_status.setEnabled(true);
		sprinkler_status.setSelectedItem(scheduler.getSprinkler().getName());
		try {
			fromTimeSpinner.setValue(new SimpleDateFormat("HH:mm").parse(scheduler.getStarttime()));
			toTimeSpinner.setValue(new SimpleDateFormat("HH:mm").parse(scheduler.getEndtime()));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		chckbxMon.setSelected(scheduler.isMon());
		chckbxTue.setSelected(scheduler.isTue());
		chckbxWed.setSelected(scheduler.isWed());
		chckbxThu.setSelected(scheduler.isThur());
		chckbxFri.setSelected(scheduler.isFri());
		chckbxSat.setSelected(scheduler.isSat());
		chckbxSun.setSelected(scheduler.isSun());
	}
	
	public boolean validateSchedule(){
		boolean val = true;
		String fromTime;
		String toTime;
		// Check at least one group should be selected if group is selected	
		if (groupBtn.isSelected()){
			
			if (!northBtn.isSelected()  &&  !westBtn.isSelected() && !eastBtn.isSelected() && !southBtn.isSelected()){
				JOptionPane.showMessageDialog(null, "Please select at least one group!");
				val = false;
			}
		}
		if (!(chckbxFri.isSelected() | (chckbxMon.isSelected()) | (chckbxSat.isSelected()) | (chckbxSun.isSelected()) | (chckbxThu.isSelected()) | (chckbxTue.isSelected()) | (chckbxWed.isSelected()))){ 
			JOptionPane.showMessageDialog(null, "Please select at least one day for schedule!");
			val = false;
		}
		// Check at least one sprinkler should be selected if schedule is selected	
		if (sprinklerBtn.isSelected()){
			
			if (sprinkler_status.getSelectedIndex() == 0){
				JOptionPane.showMessageDialog(null, "Please select sprinkler number!");
				val = false;
			}
		}
		
		fromTime =  CommonUtils.transferTime((Date) fromTimeSpinner.getValue());
		toTime =  CommonUtils.transferTime((Date) toTimeSpinner.getValue());
	
		// Check ToTime is greater than fromTime
		if (toTime.compareTo(fromTime)<= 0)
		{
			JOptionPane.showMessageDialog(null, "To time should be greater than from time.");
			val = false;
		}
		
		return val;
	}
	
	public static void refreshSchedulerPanel(){
		if (groupBtn.isSelected()){
			if (northBtn.isSelected()) {
				criteria.clear();
				criteria.put("groupName", northBtn.getText());
				SchedulePanel.setScheduleInfoData(criteria);
			}
			if (southBtn.isSelected()) {
				criteria.clear();
				criteria.put("groupName", southBtn.getText());
				SchedulePanel.setScheduleInfoData(criteria);
			}
			if (eastBtn.isSelected()) {
				criteria.clear();
				criteria.put("groupName", eastBtn.getText());
				SchedulePanel.setScheduleInfoData(criteria);
			}
			if (westBtn.isSelected()) {
				criteria.clear();
				criteria.put("groupName", westBtn.getText());
				SchedulePanel.setScheduleInfoData(criteria);
			}
		}
		if (sprinklerBtn.isSelected()){
			int i=sprinkler_status.getSelectedIndex();
			if (i>0) {
				criteria.clear();
				criteria.put("sprinklerName",sprinkler_status.getSelectedItem().toString().trim());
				SchedulePanel.setScheduleInfoData(criteria);
			}
		}
		
	}
	
	
}
